package com.wdzg.member.generate.freemaker.generator;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.wdzg.member.generate.freemaker.generator.bean.StringValue;
import com.wdzg.member.generate.freemaker.generator.bean.XmlBean;
import com.wdzg.member.generate.freemaker.generator.element.ControllerGenerator;
import com.wdzg.member.generate.freemaker.generator.element.JsGenerator;
import com.wdzg.member.generate.freemaker.generator.element.ServiceGenerator;
import com.wdzg.member.generate.freemaker.generator.element.ShowGenerator;
import com.wdzg.member.generate.freemaker.generator.metadata.JDBCMsg;

/**
 * 自动生成的工厂类
 * 
 * @author airgilbert
 *
 */
public class GeneratorFactory {
	public XmlBean bean = null;
	/**
	 * xml的类路径
	 */
	public String xmlPath = null;
	public XStream xstream = null;
	{
		xstream = new XStream(new DomDriver());
		xstream.autodetectAnnotations(true);
		xstream.alias("bean", XmlBean.class);
		xstream.alias("path", StringValue.class);
		xstream.alias("comboMaps", Map.class);
		xstream.alias("string", String.class);
		xstream.alias("columns", List.class);
	}

	public GeneratorFactory(XmlBean bean) {
		this.bean = bean;
	}
	
	/**
	 * 
	 * @param xmlPath 提供的地址为类路径，例如：com/wdip/base/utils/freemaker/ftl/user.xml
	 */
	public GeneratorFactory(String xmlPath) {
		bean = (XmlBean) xstream.fromXML(new File(XmlBean.class.getResource("/").getPath() + xmlPath));
	}

	/**
	 * 生成js
	 * 
	 * @return
	 */
	public JsGenerator createJs() {
		return new JsGenerator(bean);
	}

	/**
	 * 生成show
	 * 
	 * @return
	 */
	public ShowGenerator createShow() {
		return new ShowGenerator(bean);
	}
	
	/**
	 * 生成Controller
	 */
	public ControllerGenerator createController(){
		return new ControllerGenerator(bean);
	}
	
	/**
	 * 生成Service
	 */
	public ServiceGenerator createService(){
		return new ServiceGenerator(bean);
	}
	
	/**
	 * 生成所有模板
	 * @param ftlPath
	 */
	public void generatorAll(String ftlPath){
		createShow().generatorHtml(ftlPath);
		createJs().generatorHtml(ftlPath);
		createController().generatorHtml(ftlPath);
		createService().generatorHtml(ftlPath);
	}
	
	public static void main(String[] args) {
		//GeneratorFactory gf = new GeneratorFactory("com/wdip/base/utils/freemaker/xml/company/user.xml");
		String ftlPath = "com/wdzg/member/generate/freemaker/ftl";
		GeneratorFactory gf = new GeneratorFactory(JDBCMsg.getBean(args[0]));
		
		// 生成代码
		//if (Arrays.binarySearch(args, "generate") > -1) {
			// 生成web层代码
			gf.createShow().generatorHtml(ftlPath);
			gf.createJs().generatorHtml(ftlPath);
			
			// 生成后端代码
			gf.createController().generatorHtml(ftlPath);
			gf.createService().generatorHtml(ftlPath);
		//}
	}
}
